<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box{
            width: 400px;
            height: 400px;
            border: 10px solid #000;
            margin: 40px auto;
            position: relative;
        }
        .a{
            width: 100px;
            height: 100px;
            background-color: #f00;
            position: absolute;
            /* 禁止用户选中 */
            -webkit-user-select: none;
        }
    </style>
</head>
<body>

    <div class="box">
        <div class="a"></div>
    </div>

    <script>

        var oBox = document.querySelector('.box') ;
        var oA = document.querySelector('.a') ;

        var _left = oBox.offsetLeft ;
        var _top = oBox.offsetTop ;
        var maxW = oBox.clientWidth - oA.offsetWidth ;
        var maxH = oBox.clientHeight - oA.offsetHeight ;
        var bd = getCss(oBox , 'borderWidth') ;


        // 给小盒子绑定鼠标按下
        oA.onmousedown = function(e) {

            // 获取鼠标在盒子中的位置
            var gapX = e.offsetX ;
            var gapY = e.offsetY ;

            // 移动写给box
            oBox.onmousemove = function(e) {
                var x = e.x - gapX - _left - bd;
                var y = e.y - gapY - _top - bd ;
                if(x < 0) x = 0 ; 
                if(y < 0) y = 0 ;
                if(x > maxW) x = maxW ;
                if(y > maxH) y = maxH ;
                oA.style.cssText = `left:${x}px;top:${y}px` ;
            }

            // 鼠标抬起事件建议给  document   
            document.onmouseup = function() {
                oBox.onmousemove = null ;
                document.onmouseup = null ;
            }
        }





        function getCss(obj , prop) {
            if(window.getComputedStyle) {
                return parseInt(getComputedStyle(obj)[prop]) ;
            }
            return parseInt(obj.currentStyle[prop])
        }


    </script>
    
</body>
</html>